"""
投资分析报告窗口
"""
import os
import logging
from PyQt6.QtWidgets import QDialog, QVBoxLayout, QTextBrowser, QPushButton, QHBoxLayout, QLabel
from PyQt6.QtCore import Qt, QSize
from PyQt6.QtGui import QIcon, QColor

logger = logging.getLogger(__name__)

class InvestmentReportDialog(QDialog):
    """投资分析报告窗口，用于显示投资分析报告"""
    
    def __init__(self, goods_id, goods_name, report_file, parent=None):
        super().__init__(parent)
        self.goods_id = goods_id
        self.goods_name = goods_name or f"商品ID: {goods_id}"
        self.report_file = report_file
        self.setWindowTitle(f"投资分析报告 - {self.goods_name}")
        self.resize(800, 600)
        self.setWindowFlags(self.windowFlags() | Qt.WindowType.WindowMaximizeButtonHint)
        
        self.setup_ui()
        self.load_text_file()
        
    def setup_ui(self):
        """设置UI"""
        layout = QVBoxLayout(self)
        
        # 商品信息
        info_layout = QHBoxLayout()
        self.goods_id_label = QLabel(f"商品ID: {self.goods_id}")
        self.goods_name_label = QLabel(f"商品名称: {self.goods_name}")
        info_layout.addWidget(self.goods_id_label)
        info_layout.addWidget(self.goods_name_label)
        info_layout.addStretch()
        layout.addLayout(info_layout)
        
        # 文件路径显示
        self.path_label = QLabel(f"报告文件: {self.report_file or '未指定'}")
        layout.addWidget(self.path_label)
        
        # 文本浏览器
        self.text_browser = QTextBrowser()
        self.text_browser.setOpenExternalLinks(True)
        self.text_browser.setStyleSheet("""
            QTextBrowser {
                font-family: 'Microsoft YaHei', Arial, sans-serif;
                font-size: 14px;
                line-height: 1.6;
                background-color: #ffffff;
                padding: 10px;
                border: 1px solid #e0e0e0;
                border-radius: 4px;
            }
        """)
        layout.addWidget(self.text_browser)
        
        # 底部按钮
        button_layout = QHBoxLayout()
        
        self.close_button = QPushButton("关闭")
        self.close_button.setFixedSize(QSize(100, 30))
        self.close_button.clicked.connect(self.close)
        
        button_layout.addStretch()
        button_layout.addWidget(self.close_button)
        
        layout.addLayout(button_layout)
        
    def load_text_file(self):
        """加载文本文件并显示"""
        if not self.report_file or not os.path.exists(self.report_file):
            self.text_browser.setHtml("<h2>无法加载投资分析报告</h2><p>文件不存在或路径无效</p>")
            self.path_label.setText(f"报告文件: {self.report_file or '未指定'} (不存在)")
            return
        
        try:
            with open(self.report_file, 'r', encoding='utf-8') as f:
                content = f.read()
            
            # 使用正则表达式处理Markdown格式
            import re
            
            # 预处理：确保每个标题前后都有换行
            content = re.sub(r'([^\n])(\n?)(#+ )', r'\1\n\n\3', content)
            
            # 处理独立的粗体行（**内容**）- 需要独立一行显示
            content = re.sub(r'^(\*\*[^*\n]+\*\*)$', r'<div class="bold-line">\1</div>', content, flags=re.MULTILINE)
            
            # 处理标题
            content = re.sub(r'^# (.*?)$', r'<h1>\1</h1>', content, flags=re.MULTILINE)
            content = re.sub(r'^## (.*?)$', r'<h2>\1</h2>', content, flags=re.MULTILINE)
            content = re.sub(r'^### (.*?)$', r'<h3>\1</h3>', content, flags=re.MULTILINE)
            
            # 处理列表项中的粗体（- **内容**）- 不需要独立显示
            content = re.sub(r'^- \*\*(.*?)\*\*(.*)$', r'<li><span class="bold">\1</span>\2</li>', content, flags=re.MULTILINE)
            
            # 处理其他列表项
            content = re.sub(r'^- (.*?)$', r'<li>\1</li>', content, flags=re.MULTILINE)
            
            # 处理行内粗体（不在行首的情况）
            content = re.sub(r'(?<![*\n])\*\*(.*?)\*\*', r'<span class="bold">\1</span>', content)
            
            # 处理斜体 (避免与粗体冲突)
            content = re.sub(r'\*([^*]+)\*', r'<i>\1</i>', content)
            
            # 处理代码块
            content = re.sub(r'```(.*?)```', r'<pre><code>\1</code></pre>', content, flags=re.DOTALL)
            
            # 处理行内代码
            content = re.sub(r'`([^`]+)`', r'<code>\1</code>', content)
            
            # 处理分隔线
            content = re.sub(r'^---+$', r'<hr>', content, flags=re.MULTILINE)
            
            # 处理链接
            content = re.sub(r'\[(.*?)\]\((.*?)\)', r'<a href="\2">\1</a>', content)
            
            # 处理段落：确保段落之间有适当的间距
            # 先将连续的非空行组合成段落
            content = re.sub(r'([^\n]+)\n(?!\n|<h|<li|<pre|<hr|<div)', r'\1 ', content)
            # 然后给每个段落添加标签
            content = re.sub(r'([^\n]+)(\n\n|$)', r'<p>\1</p>\2', content)
            
            # 处理特定的投资报告格式
            # 价格信息高亮
            content = re.sub(r'(\d+\.\d+元)', r'<span class="price">\1</span>', content)
            
            # 投资建议颜色区分
            content = re.sub(r'(值得投资|建议买入|看涨|bullish)', r'<span class="positive">\1</span>', content)
            content = re.sub(r'(不建议投资|建议卖出|看跌|bearish)', r'<span class="negative">\1</span>', content)
            content = re.sub(r'(建议观望|中性|neutral)', r'<span class="neutral">\1</span>', content)
            
            # 添加基本样式
            styled_html = f"""
            <html>
            <head>
                <style>
                    body {{
                        font-family: 'Microsoft YaHei', Arial, sans-serif;
                        line-height: 1.6;
                        color: #333;
                        max-width: 100%;
                        margin: 0;
                        padding: 20px;
                    }}
                    h1, h2, h3, h4, h5, h6 {{
                        margin-top: 24px;
                        margin-bottom: 16px;
                        font-weight: 600;
                        color: #0366d6;
                        clear: both;
                    }}
                    h1 {{ font-size: 2em; border-bottom: 1px solid #eaecef; padding-bottom: .3em; }}
                    h2 {{ font-size: 1.5em; border-bottom: 1px solid #eaecef; padding-bottom: .3em; }}
                    h3 {{ font-size: 1.25em; }}
                    p {{ 
                        margin-bottom: 16px; 
                        text-align: justify;
                    }}
                    ul, ol {{ 
                        padding-left: 2em; 
                        margin-bottom: 16px;
                    }}
                    li {{ 
                        margin: 0.5em 0; 
                        list-style-position: outside;
                    }}
                    pre {{
                        background-color: #f6f8fa;
                        border-radius: 3px;
                        padding: 16px;
                        overflow: auto;
                        margin-bottom: 16px;
                    }}
                    code {{
                        background-color: #f6f8fa;
                        padding: 0.2em 0.4em;
                        border-radius: 3px;
                        font-family: SFMono-Regular, Consolas, Liberation Mono, Menlo, monospace;
                        font-size: 85%;
                    }}
                    pre code {{
                        background-color: transparent;
                        padding: 0;
                        border-radius: 0;
                    }}
                    blockquote {{
                        padding: 0 1em;
                        color: #6a737d;
                        border-left: 0.25em solid #dfe2e5;
                        margin: 0 0 16px 0;
                    }}
                    table {{
                        border-collapse: collapse;
                        width: 100%;
                        margin-bottom: 16px;
                    }}
                    table, th, td {{
                        border: 1px solid #dfe2e5;
                    }}
                    th, td {{
                        padding: 6px 13px;
                    }}
                    th {{
                        background-color: #f6f8fa;
                    }}
                    tr:nth-child(even) {{
                        background-color: #f6f8fa;
                    }}
                    a {{
                        color: #0366d6;
                        text-decoration: none;
                    }}
                    a:hover {{
                        text-decoration: underline;
                    }}
                    .highlight {{
                        background-color: #fffbdd;
                        padding: 2px;
                    }}
                    .price {{
                        font-weight: bold;
                        color: #0366d6;
                    }}
                    .positive {{
                        color: #28a745;
                        font-weight: bold;
                    }}
                    .negative {{
                        color: #d73a49;
                        font-weight: bold;
                    }}
                    .neutral {{
                        color: #6a737d;
                        font-weight: bold;
                    }}
                    .bold {{
                        font-weight: bold;
                    }}
                    .bold-line {{
                        font-weight: bold;
                        display: block;
                        margin: 10px 0;
                    }}
                </style>
            </head>
            <body>
                <div>
                {content}
                </div>
            </body>
            </html>
            """
            
            self.text_browser.setHtml(styled_html)
            
        except Exception as e:
            logger.error(f"加载文件时出错: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            self.text_browser.setHtml(f"<h2>加载文件时出错</h2><p>错误信息: {str(e)}</p>")
